<?php
/**
 * 数据库备份还原
 * 依赖于数据库底层驱动
 * @todo 待完善
 * @author ximu
 */
class T_mysqlbak extends base{
	
	/*
	 * 数据库对象
	 */
	private $_db = null;
	
	/*
	 * 数据库名称
	 */
	private $_dbName = '';
	
	/*
	 * 表名称
	 */
	private $_tableName = '';
	
	/*
	 * 输出流方式
	 */
	
	private $_flow = false;
	
	/**
	 * 构造函数
	 * @param object $db
	 * @param string $dbname
	 */
	public function __construct($drive,$dbName,$tableName){
		parent::__construct();
		$this->_db = $drive;
		$this->_dbName = $dbName;
		$this->_tableName = $tableName;
		$this->_db->query("USE {$this->_dbName}");
	}
	
	/**
	 * 数据库备份 
	 */
	public function bak(){
		$sql = $this->_getHead();
		$sql .= $this->_getCreateSql();
		$sql .= $this->_getDataSql();
		return sql;
	}
	
	/**
	 * 文件流形式备份
	 */
	public function flowBak(){
		header("Content-Type: text/sql");
		$time = date('Y-m-d-H-i-s');
		header("Content-Disposition: attachment; filename={$time}.sql");
		$this->_flow = true;
		$sql = $this->_getHead();
		$sql .= $this->_getCreateSql();
		$sql .= $this->_getDataSql();
	}
	
	/**
	 * 数据库还原
	 */
	public function restore(){
		
	}
	
	/**
	 * 获取统一头部
	 */
	private function _getHead(){
		$time = date('Y-m-d H:i:s');
		$head = "/*SQLBAK TIME:{$time} DB:{$this->_dbName} TABLE:{$this->_tableName}*/"."\r\n";
		$head .= "USE `{$this->_dbName}`;\r\n";
		if($this->_flow)	echo $head;
		return $head;
	}
	
	/**
	 * 获取创建表sql
	 */
	private function _getCreateSql()
	{
		$result = $this->_db->query("SHOW CREATE TABLE `{$this->_tableName}`");
		$existSql = "DROP TABLE IF EXISTS `{$this->_tableName}`;"."\r\n";
		$sql = $existSql.end($result[0]).";\r\n";
		if($this->_flow)	echo $sql;
		return $sql;
	}
	
	/**
	 * 获取表数据
	 */
	private function _getDataSql(){
		$count = $this->_db->table($this->_tableName)->getCount();
		$sql = '';
		for($i=0;$i<$count;$i=$i+20){
			$data = $this->_db->table($this->_tableName)->limit($i,20)->getAll();
			foreach($data as $vv){
				$field = $value ='';
				foreach($vv as $k=>$v){
					$field .= (empty($field)?'`':',`').$k.'`';
					$value .= (empty($value)?'':',').mysql_escape_string($v);
				}
				if($this->_flow)
					echo $sql = 'INSERT INTO `'.$this->_tableName.'` ('.$field.') VALUES ('.$value.');'."\r\n";
				else
					$sql .= 'INSERT INTO `'.$this->_tableName.'` ('.$field.') VALUES ('.$value.');'."\r\n";
			}
		}
		return $sql;
	}
	
	/**
	 * 异常
	 */
	private function _throw($message,$code)
	{
	}
}
?>